package com.ruoyi.cat.service.impl;

import com.ruoyi.cat.domain.*;
import com.ruoyi.cat.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@Service
@Slf4j
public class ActivityImpl implements ActivityService {

    @Autowired
    private ICatIprecordTableService ipRecordService;

    @Autowired
    private ICatActivityTableService activityService;

    @Autowired
    private ICatUserbasicTableService userService;

    @Autowired
    private ICatTradedetailTableService tradeDetailService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void processActivityReward(CatIprecordTable record, CatBasedataTable baseData) {
        // 获取活动信息
        CatActivityTable activity = activityService.selectCatActivityTableByIdTask(record.getArticleId());
        if (activity == null) {
            log.warn("活动不存在，活动ID：{}", record.getArticleId());
            return;
        }
        // 查询用户是否存在
        CatUserbasicTable sharer = userService.selectCatUserbasicTableById(record.getShareUserId());
        if (sharer == null) {
            log.warn("用户不存在，用户ID：{}", record.getShareUserId());
            return;
        }
        //获取用户分享的总UV数量
        Long totalUvCount = getTotalUvCount(record);
        if (totalUvCount == 0) {
            log.info("活动没有访问量，跳过处理，活动ID: {}, 用户ID: {}", activity.getId(), sharer.getId());
            return;
        }
        //每个活动阅读量单价
        BigDecimal activityBaseCost = activity.getActivityBaseCost();
        // 计算活动收益
        BigDecimal introduceReward = baseData.getIntroduceReward().divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP);


        /**
         * 个人收益=活动阅读量单价*活动总UV数量
         */
        BigDecimal personalReward = BigDecimal.valueOf(totalUvCount)
                .multiply(activityBaseCost)
                .setScale(2, RoundingMode.HALF_UP);

        log.info("用户[ID:{}]活动[ID:{}] 活动个人收益：{}", sharer.getId(), activity.getId(), personalReward);

       /* 团队助力:
        下线产生的UV总数*基础数据设置表(BaseData Table)
        中OffsiteDiscountRate字段，再*H5活动表(Activity Table)
        中ActivityBaseCost字段*/
        List<CatUserbasicTable> list =  getTotalUvCountX(record);
        for (CatUserbasicTable catUserbasicTable : list) {
            record.setShareUserId(catUserbasicTable.getId());
           // record.setAreaValue(activity.getArea());
            record.setAreaValue(activity.getCity());
            //本地ip数量
            CatIprecordTable localRecord1= ipRecordService.getStaskData(record);
            //异地ip数量
            CatIprecordTable remoteRecord2 = ipRecordService.getStaskDataNo(record);
            // 初始化本地和异地访问量
            Long localQuantity1 = (localRecord1!= null)? localRecord1.getQuantity() : 0L;
            Long remoteQuantity2 = (remoteRecord2!= null)? remoteRecord2.getQuantity() : 0L;

            if (remoteQuantity2 > 0) {
                // 计算本地收益：introduceReward * 异地IP数
                BigDecimal localReward1 = introduceReward
                        .multiply(BigDecimal.valueOf(remoteQuantity2))
                        .setScale(2, RoundingMode.HALF_UP);
                log.info("下级给我的收益：{} ",localReward1);

                recordTradeDetail(sharer, activity.getId(), sharer.getId(),
                        localReward1, catUserbasicTable.getId(), "3",
                        null, "活动推广收益", "2");
            }


            Long count = localQuantity1+remoteQuantity2;
            log.info("count:{}",count);
            log.info("activityBaseCost {}",activityBaseCost);
           // Long count =  ipRecordService.countShareRecord(record);
            count = count != null ? count : 0L;
            if (count > 0) {
                BigDecimal teamReward = BigDecimal.valueOf(count)
                        .multiply(baseData.getOffsiteDiscountRate())
                        .multiply(activityBaseCost)
                        .setScale(2, RoundingMode.HALF_UP);

                log.info("用户[ID:{}]活动[ID:{}]团队产生收益：{}", sharer.getId(), activity.getId(), teamReward);
                // 计算推荐人获得的助力数量
                long helpingPeople = Math.round(count * introduceReward.doubleValue());
                recordTradeDetail(
                        sharer,
                        activity.getId(),
                        sharer.getId(),
                        personalReward,
                        catUserbasicTable.getId(),
                        "0",
                        helpingPeople,
                        "活动任务团队助力收益",
                        "2"
                );
            }
        }
        log.info("用户[ID:{}]活动[ID:{}] 活动团队助力收益：{}", sharer.getId(), activity.getId(), personalReward);
        record.setShareUserId(sharer.getId());
        //查询父类,给父类产生收益

        //本地ip数量
        CatIprecordTable localRecord1= ipRecordService.getStaskData(record);
        //异地ip数量
        CatIprecordTable remoteRecord2 = ipRecordService.getStaskDataNo(record);
        // 初始化本地和异地访问量
        Long localQuantity1 = (localRecord1!= null)? localRecord1.getQuantity() : 0L;
        Long remoteQuantity2 = (remoteRecord2!= null)? remoteRecord2.getQuantity() : 0L;
        Long count = localQuantity1+remoteQuantity2;
      //  Long count =  ipRecordService.countShareRecord(record);
        if (sharer.getReferenceId() != null && remoteQuantity2 > 0) {
            CatUserbasicTable referrer = userService.selectCatUserbasicTableById(sharer.getReferenceId());
            if (referrer != null) {
                BigDecimal localReward1 = introduceReward
                        .multiply(BigDecimal.valueOf(remoteQuantity2))
                        .setScale(2, RoundingMode.HALF_UP);
                log.info("我给上级的收益：{} ",localReward1);
                log.info("我的收益：{} ",personalReward);
                long helpingPeople = Math.round(count * introduceReward.doubleValue());
              //  personalReward = personalReward.subtract(localReward1);
                if (localReward1.compareTo(personalReward) <= 0) {
                    personalReward = personalReward.subtract(localReward1);
                    log.info("实际扣除上级收益后剩余金额：{}", personalReward);
                } else {
                    log.warn("上级收益 {} 超过个人总收益 {}，不进行扣除", localReward1, personalReward);
                }
                // 记录推荐人获得的收益
                recordTradeDetail(
                        referrer,
                        activity.getId(),
                        referrer.getId(),
                        localReward1,
                        sharer.getId(),
                        "0",
                        null,
                        "活动推广收益",
                        "4"
                );
            }
        }
        //收益的值
       // personalReward
        recordTradeDetail(
                sharer,
                activity.getId(),
                sharer.getId(),
                personalReward,
                null,
                "0",
                0L,
                "活动推广收益",
                "2"
        );
    }


    /**
     * 记录交易明细
     */
    private void recordTradeDetail(CatUserbasicTable user, Long activityId, Long userId,
                                   BigDecimal amount, Long profitUserId, String income,
                                   Long helpingPeople, String tradeTitle, String type) {
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            return; // 金额为零或负数不记录
        }

        CatTradedetailTable tradeDetail = new CatTradedetailTable();
        tradeDetail.setActivityId(activityId);
        tradeDetail.setUserId(userId);
        tradeDetail.setTradeType("0"); // 未结算
        tradeDetail.setTradeTitle(tradeTitle);
        tradeDetail.setTradeNum(amount);
        tradeDetail.setType(type);
        tradeDetail.setProfitUserId(profitUserId);
        tradeDetail.setIncome(income);
        tradeDetail.setHelpingPeople(helpingPeople);

        // 插入交易记录
        tradeDetailService.insertCatTradedetailTable(tradeDetail);

        // 更新用户冻结余额
        updateUserBalance(user, amount);

        log.info("记录交易明细成功：用户ID={}，活动ID={}，金额={}，类型={}",
                userId, activityId, amount, type);
    }

    /**
     * 获取用户分享的总UV数量
     */
    private Long getTotalUvCount(CatIprecordTable record) {
        // 活动不区分省内省外，直接获取总UV
        CatIprecordTable uvCountRecord = ipRecordService.getTotalUvCount(record);
        return uvCountRecord != null ? uvCountRecord.getQuantity() : 0L;
    }

    /**
     * 获取所有下线产生的UV总数
     * @param record
     * @return
     */
    private  List<CatUserbasicTable> getTotalUvCountX(CatIprecordTable record) {
        List<CatUserbasicTable> list =  userService.countByReferenceData(record.getShareUserId());
        return list;
    }

    /**
     * 更新用户冻结余额
     */
    private void updateUserBalance(CatUserbasicTable user, BigDecimal amount) {
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            return; // 金额为零或负数不处理
        }

        // 处理冻结金额为null的情况
        BigDecimal freezeDeposits = user.getFreezeDeposits() != null ? user.getFreezeDeposits() : BigDecimal.ZERO;
        user.setFreezeDeposits(freezeDeposits.add(amount));

        int result = userService.updateCatUserbasicTable(user);
        if (result != 1) {
            log.warn("更新用户冻结余额失败，用户ID：{}", user.getId());
        }
    }
}
